package com.vains.exception;

import com.vains.enumeration.ResultEnum;
import com.vains.io.JsonUtils;
import com.vains.system.model.ErrorTokenModel;
import com.vains.system.model.Result;
import com.vains.system.util.ResultUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) {
        Throwable cause = authException.getCause();
        response.setStatus(HttpStatus.OK.value());
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        try {
            if(cause instanceof InvalidTokenException) {
                Result<ErrorTokenModel> tokenModelResult = new Result<>();
                ErrorTokenModel tokenModel = JsonUtils.jsonCovertToObject(cause.getMessage(), ErrorTokenModel.class);
                tokenModelResult.setCode(ResultEnum.ERROR.getCode());
                tokenModelResult.setData(tokenModel);
                tokenModelResult.setSuccess(false);
                tokenModelResult.setMessage(tokenModel.getCause());
                response.getWriter().write(JsonUtils.objectCovertToJson(tokenModelResult));
            }else{
                response.getWriter().write(JsonUtils.objectCovertToJson(ResultUtils.error("令牌无效, 请检查令牌是否正确!")));
            }
        } catch (IOException e) {
            throw new CustomerException("令牌失效, 响应失败!");
        }
    }
}
